<?php
/**
 * Created by PhpStorm .
 * User: {Administrator}
 * Date: {2022/7/8 16:42}
 * Author: '树叶'
 * Email: 'ayunu@qq.com'
 * Motto Info: '理想如果不向现实做一点点屈服，那么理想也将归于尘土。'
 */

namespace app\api\model;
use fast\Pinyin;
use think\Model;
use think\Db;

class UserCar extends Model
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = '';
    protected $updateTime = '';
    protected $resultSetType = 'collection';
    // 追加属性
    protected $append = [

    ];

    /**
     * 热门厂牌
     */
    public function getHot()
    {
        $res = Db::name('vehicle')->where('pid',0)->where("del",0)->where('flag','hot')->select();
        $http = http_url_img();

        foreach ($res as $key => &$val)
        {
            if (!filter_var($val['logo'],FILTER_VALIDATE_URL))
            {
                $val['logo'] = $http.$val['logo'];
            }
        }
        return $res;
    }

    /**
     * 车型列表
     */
    public function Getmodels($id = '',$name = '')
    {
        if ($id)
        {
            $where = [];
            if ($name)
            {
                $where['mergename'] = ['like','%'.$name.'%'];
                $where['pid'] = ['eq',0];
                $list = Vehicle::where($where)->where("del",0)->select();
                return $list;
            }
            $vechiclelist = Db::name('vehicle')->where("del",0)->where('pid',$id)->select();
        }else{
            $vechiclelist = Db::name('vehicle')->where("del",0)->where('pid',0)->select();
        }

        $http = http_url_img();
        foreach ($vechiclelist as $key => &$val)
        {
            $vechiclelist[$key]['sort'] = Pinyin::get($val['mergename']);
            if (!filter_var($val['logo'],FILTER_VALIDATE_URL))
            {
                $val['logo'] = $http.$val['logo'];
            }
        }

        $sort = array_column($vechiclelist,'sort');
        array_multisort($sort,SORT_DESC,$vechiclelist);
   
       return $vechiclelist;
    }

    /**
     * @param $data
     * @return false|int|string
     * 添加车型
     */
    public function add($data)
    {

        if (!$data) return false;
        $label = Db::name('vehicle')->where('id',$data['label'])->where('pid',0)->find();

        if (!$label){return false;}
        $brand = Db::name('vehicle')->where('id',$data['brand'])->find(); // 车型

        if ($brand['pid'] != $label['id'] ){

            return false;}
        $year = Db::name('vehicle')->where('id',$data['year'])->find();  // 年份

        if ($year['pid'] != $brand['id'] ){return false;}
        $engine = Db::name('vehicle')->where('id',$data['engine'])->find(); // 排量

        if ($engine['pid'] != $year['id'] ){return false;}

        $models = Db::name('vehicle')->where('id',$data['models'])->find(); // 款型

        if ($models['pid'] != $engine['id']){return false;}
        $res = Db::name('user_car')->insertGetId($data);
        return $res;
    }

    /**
     * @param $cid
     * @param $pid
     * @param $plate
     * @param $frame
     * @return array
     * 添加车辆信息
     */
    public function addPlate($cid, $pid, $plate, $frame)
    {
        $result = [
            'data' => [],
            'msg'  => '',
            'status'  => false,
        ];
        $userCar = Db::name('user_car')->where('id',$cid)->find();
        if (!$userCar)
        {
            $result['msg'] = '车辆信息不存在';
            return $result;
        }

        $provCity = Db::name('prov_city')->where('id',$pid)->find();
        if (!$provCity)
        {
            $result['msg'] = '请从新选择前缀信息';
            return $result;
        }
        $province_code = $provCity['province_code'];
        $city_code     = $provCity['city_code'];
        $province_city = $province_code.''.$city_code.' '.$plate;
        $data = [
            'car_id' => $cid,
            'plate_number' => $province_city,
            'frame_number' => $frame,
        ];
        $carbinding = Db::name('car_information')->where('car_id',$cid)->find();

        $carInformation = Db::name('car_information')->where('plate_number',$province_city)->find();
        if ($carInformation)
        {
            $result['msg'] = '车牌已绑定,请检查您的车牌号';
            return $result;
        }

        if ($carbinding)
        {
            $result['msg'] = '您添加的车型已绑定,请从新操作';
            return $result;
        }
        $response = Db::name('car_information')->insertGetId($data);
        if ($response)
        {
            $result['data']   = $response;
            $result['status'] = true;
        }
        return $result;
    }
    /**
     * 车牌列表
     */
    public function getPlate()
    {
        $res = Db::name('prov_city')
            ->field('id,province_code,city_code')
            ->where('status',0)
            ->select();
        return $res;
    }
    /**
     * 车型列表
     */
    public function getlist($uid)
    {
        $carlist = Db::name('user_car')->where('uid',$uid)->select();
        $http = http_url_img();
        foreach ($carlist as $key => $val)
        {
            $logo = Db::name('vehicle')->where('id',$val['label'])->value('logo');
           
            if (empty($logo))
            {
                $carlist[$key]['logo'] = '';
            }else{
                $carlist[$key]['logo']  = filter_var($logo,FILTER_VALIDATE_URL) != true ? $logo : $logo; // logo
            }
            $carlist[$key]['label']  = Db::name('vehicle')->where('id',$val['label'])->value('mergename');  //  厂牌
            $carlist[$key]['brand']  = Db::name('vehicle')->where('id',$val['brand'])->value('mergename');  //  车型
            $carlist[$key]['year']   = Db::name('vehicle')->where('id',$val['year'])->value('mergename');   //  年份
            $carlist[$key]['engine'] = Db::name('vehicle')->where('id',$val['engine'])->value('mergename'); // 发动机
            $carlist[$key]['models'] = Db::name('vehicle')->where('id',$val['models'])->value('mergename'); // 款型
        }

        return $carlist;
    }
    /**
     * 爱车详情
     */
    public function getCardetails($id, $uid)
    {
        $result = [
            'data'    => [
                'cardata' => [],    //车型
                'carplate' => null //车牌
            ],
            'msg'     => '',
            'status'  => false,
        ];
        $user = Db::name('user')->where('id',$uid)->find();
        if (!$user)
        {
            $result['msg'] = '用户不存在';
            return $result;
        }
        $car = Db::name('user_car')->where('id',$id)->where('uid', $uid)->find();

        if (!$car)
        {
            $result['msg'] = '没有添加车型';
            return $result;
        }
        $cardata = [];
        $cardata['brand']  = Db::name('vehicle')->where('id',$car['brand'])->value('mergename');
        $cardata['engine'] = Db::name('vehicle')->where('id',$car['engine'])->value('mergename');
        $cardata['models'] = Db::name('vehicle')->where('id',$car['models'])->value('mergename');
        $cardata['label']  = Db::name('vehicle')->where('id',$car['label'])->value('mergename');
        $cardata['year']   = Db::name('vehicle')->where('id',$car['year'])->value('mergename');
        $cardata['logo']   = Db::name('vehicle')->where('id',$car['brand'])->value('logo');
        $result['data']['cardata'] = $cardata;
        $plate = Db::name('car_information')->where('car_id',$id)->find();
        if (!$plate)
        {
            $result['status'] = true;
            return $result;
        }
        $result['status'] = true;
        $result['data']['carplate'] = $plate;
        $result['data']['msg']      = '添加成功';
        return $result;
    }

    /**
     * 更新默认状态
     */
    public function upDefault($id = 0, $uid)
    {
        $car = Db::name('user_car')->where('id',$id)->find();
        Db::startTrans();
        try {
            if($car){

                $res = Db::name('user')
                    ->where('id',$uid)
                    ->update([
                        'cartype' => $car['id'],
                        'models'  => $car['brand']
                    ]);
                Db::commit();
            }else{
                $res = false;
            }

        }catch(\Exception $e){
            Db::rollback();
            var_dump($e->getMessage());
            $res = false;
        }
        return $res;
    }

    /**
     * 删除爱车
     * @param $uid
     * @param string $ids 绑定id
     * @return array
     */
    public function del($uid,$ids = '')
    {
        $result = [];
        $result['msg']    = '';
        $result['status'] = false;
        Db::startTrans();
        try {
           $rescar = Db::name('user_car')->where('uid',$uid)->where('id','in',$ids)->delete();

           if (!$rescar)
           {
               $result['msg'] = '删除失败';
               return $result;
           }
            Db::name('car_information')->where('id','in',$ids)->delete();
            Db::commit();
            $result['msg'] = '删除成功';
            return $result;
        }catch(\Exception $e){
            var_dump($e->getMessage());
            Db::rollback();
            $result['msg'] = $e->getMessage();
            return $result;
        }

    }

    /**
     * 修改车辆信息
     */
    public function carupdate($id, $data = [])
    {
        $result = [
            'data'   => [],
            'msg'    => '缺少参数',
            'status' => false
        ];
        $usercar = Db::name('user_car')->where('id',$id)->find();
        $result['msg'] = '信息不存在';
        if (!$usercar) return $result;
        if (!$data) return $result;
        $brand = Db::name('vehicle')->where('id',$data['brand'])->where('pid',0)->find();  //厂牌
        if (!$brand)  { $result['msg'] = '厂牌不匹配'; return $result;}
        $models = Db::name('vehicle')->where('id',$data['models'])->where('pid',$brand['id'])->find(); //车型
        if (!$models) { $result['msg'] = '车型不匹配'; return $result;}
        $engine = Db::name('vehicle')->where('id',$data['engine'])->where('pid',$models['id'])->find(); //发动机
        if (!$engine) { $result['msg'] = '发动机不匹配'; return $result;}
        $year = Db::name('vehicle')->where('id',$data['year'])->where('pid',$engine['id'])->find();  // 年份
        if (!$year)   { $result['msg'] = '年份不匹配'; return $result;}
        $models = Db::name('vehicle')->where('id',$data['label'])->where('pid',$year['id'])->find(); //款型

        if (!$models)   { $result['msg'] = '款型不匹配'; return $result;}
        $res = Db::name('user_car')->where('id',$id)->update($data);

        if ($res)
        {
            $result['status'] = true;
            return $result;
        }else{
            $result['msg'] = '更新失败';
            return $result;
        }


    }


}